<!--
 * @Author: zqx me_zqx@163.com
 * @Date: 2024-08-26 17:46:45
 * @LastEditors: zqx me_zqx@163.com
 * @LastEditTime: 2025-08-27 10:52:32
 * @FilePath: /XMate-h5/src/views/customerAndBusiness/components/visitRecord/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="container">
    <div class="head-view">
      <div>共{{ listData.length }}个沟通记录</div>
    </div>

    <van-empty description="暂无内容" v-if="!listData.length" />

    <template v-else>
      <visitRecordOverview v-if="!hiddenBarChart" :processedData="processedData" />
      <div v-ai-tip class="list-view">
        <visitRecordCard
          v-for="item in listData"
          :key="item"
          :item="item"
          :tagColor="getTagColor(item)"
        />
      </div>
    </template>
  </div>
</template>

<script setup>
import { onMounted, computed, ref, defineProps } from "vue";
import visitRecordCard from "./visitRecordCard.vue";
import { useCustomerStore, useCommonStore, useBusinessStore } from "@/store";
import { generateSimilarColor } from "@/utils/colorTool";
import visitRecordOverview from "./visitRecordOverview.vue";
import datePicker from "@/components/datePicker/index.vue";
import { isPC } from "@/utils/platformTool";
import { colors21 } from "@/utils/colorTool";

const props = defineProps({
  isCustomer: {
    type: Boolean,
    default: true,
  },
});
const store = useCustomerStore();
const commonStore = useCommonStore();
const businessStore = useBusinessStore();
const listData = computed(() => {
  return props.isCustomer ? store.visitRecordList : businessStore.visitRecordList;
});

const dateRange = store.getDefaultDateRange();
// 是否存在商机
const enableBusinessOpportunity = computed(() => {
  return commonStore.enableBusinessOpportunity;
});

// 是否隐藏柱状图
const hiddenBarChart = computed(() => {
  return enableBusinessOpportunity.value && props.isCustomer;
});

const isToB = computed(() => {
  return commonStore.isToB;
});

const startDate = ref(dateRange.st);
const endDate = ref(dateRange.et);
function onSearch() {
  getData(startDate.value, endDate.value);
}

function getData(startTime, endTime) {
  if (props.isCustomer) {
    store.getVisitRecordList(startTime, endTime);
  } else {
    businessStore.getVisitRecordList(startTime, endTime);
  }
}

function getTagColor(item) {
  console.log("item: ", item);
  console.log("processedData: ", processedData.value);
  return processedData.value.find((tag) => tag.title === item.stageName)?.color;
}

const cp_communicationStages = computed(() => {
  if (props.isCustomer) {
    return store.communicationStages;
  } else {
    return businessStore.communicationStages;
  }
});

// 创建一个标签优先级映射
const tagPriority = computed(() => {
  return cp_communicationStages.value.reduce((acc, tag, index) => {
    acc[tag.name] = index; // 使用标签的索引作为优先级
    return acc;
  }, {});
});

const processedData = computed(() => {
  // 创建标签统计 Map
  const tagCountMap = new Map();

  // 统计标签出现次数
  listData.value.forEach((item) => {
    if (!item.stageName) return;
    const trimmedTag = item.stageName.trim();
    if (trimmedTag) {
      tagCountMap.set(trimmedTag, (tagCountMap.get(trimmedTag) || 0) + 1);
    }
  });

  console.log("tagCountMap: ", tagCountMap);
  // 转换为数组并计算百分比
  const data = Array.from(tagCountMap)
    .map(([title, count]) => ({ title, count }))
    .sort((a, b) => {
      // 根据系统预设的标签顺序排序（系统预设的标签是有逻辑推进关系的）
      const aPriority =
        tagPriority.value[a.title] !== undefined ? tagPriority.value[a.title] : Infinity;
      const bPriority =
        tagPriority.value[b.title] !== undefined ? tagPriority.value[b.title] : Infinity;
      console.log("aPriority: ", tagPriority, a, "bPriority: ", b);
      return aPriority - bPriority;
    });

  console.log("data: ", data);

  const total = data.reduce((sum, item) => sum + item.count, 0);
  const baseColors = colors21;
  // 添加颜色和百分比
  let arr =
    data.map((item, index) => {
      let color;
      if (index < baseColors.length) {
        color = baseColors[index];
      } else {
        const baseColor = baseColors[index % baseColors.length];
        color = generateSimilarColor(baseColor); //;
      }

      return {
        ...item,
        percentage: total ? Math.round((item.count / total) * 100) : 0,
        color,
      };
    }) || [];

  return arr;
});

onMounted(async () => {
  const dateRange = store.getDefaultDateRange();
  // await store.getSystemTagsAction();
  getData(dateRange.st, dateRange.et);
});
</script>

<style lang="less" scoped>
.container {
  padding: 15px 20px;
  box-sizing: border-box;

  .head-view {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    width: 100%;
    font-size: 14px;
    color: #595959;
    line-height: 22px;

    img {
      width: 16px;
    }
  }

  .list-view {
    margin-top: 20px;
  }
}
</style>
